package commands;

import java.util.ArrayList;

import twitter4j.internal.org.json.JSONArray;
import twitter4j.internal.org.json.JSONException;
import twitter4j.internal.org.json.JSONObject;
import database.models.MessageModel;
import database.objects.Message;
import database.objects.MessageOwner;

/**
 * Command that gets the last 10 messages from the database.
 * 
 * @author Project group 9
 * 
 */
public class GetNewMessagesCommand implements Command {

	JSONObject jsonObject;
	MessageModel messageModel;

	public GetNewMessagesCommand(JSONObject jsonObject, MessageModel messageModel) {
		this.jsonObject = jsonObject;
		this.messageModel = messageModel;
	}

	@Override
	public String execute() throws JSONException {
		JSONArray sendArray = new JSONArray();
		
		JSONArray parameters = jsonObject.getJSONArray("getNewMessages");
		ArrayList<Message> messages = messageModel.getNewMessages(functions.StaticFunctions.JSONArrayToArrayList(parameters));

		for (Message mes : messages) {
			JSONObject message = new JSONObject();
			JSONObject messageOwner = new JSONObject();
			MessageOwner owner = mes.getMessageOwner();

			messageOwner.put("id", owner.getId());
			messageOwner.put("twitter_id", owner.getTwitterId());
			messageOwner.put("name", owner.getName());
			messageOwner.put("profile_image_url", owner.getProfileImageURL());

			message.put("id", mes.getId());
			message.put("text", mes.getText());
			message.put("created_at",
					mes.getCreatedAt().toString().substring(0, 19));
			message.put("place", mes.getPlace());
			message.put("owner", messageOwner);
			message.put("tweet_id", mes.getTweetId());
			message.put("is_retweet", mes.getIsRetweet());

			sendArray.put(message);
		}
		return sendArray.toString();
	}

}
